package imageProcessing.filter;

import imageProcessing.Duplicator;
import imageProcessing.ImageEvent;
import imageProcessing.ImageListener;

import java.awt.image.renderable.ParameterBlock;
import java.util.ArrayList;

import javax.media.jai.JAI;
import javax.media.jai.KernelJAI;
import javax.media.jai.PlanarImage;

public class ClosingFilter implements ImageListener {
	float[] _ematrix = new float[] {
            1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
            1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
            1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
            1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
            1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
            1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
            1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
            1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
            1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
            1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
            1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
            1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
            1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
        };
	  float _dmatrix[] = {
	            1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
	            1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
	            1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
	            1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
	            1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
	            1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
	            1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
	            1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
	            1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
	            1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
	            1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
	        };

	private ArrayList<ImageListener> _listeners;
	private PlanarImage _image;

	public ClosingFilter() {
		_listeners = new ArrayList<ImageListener>();
		_image = null;
	}

	public void notifyListeners() {
		ImageEvent ie = new ImageEvent(this, _image);
		ArrayList<ImageListener> copy = Duplicator.copyListeners(_listeners);
		for (ImageListener listener : copy) {
			listener.imageChanged(ie);
		}
	}

	public void addImageListener(ImageListener imageListener) {
		_listeners.add(imageListener);
	}

	public void removeImageListener(ImageListener imageListener) {
		_listeners.remove(imageListener);
	}

	@Override
	public void imageChanged(ImageEvent ie) {
				
		KernelJAI kernel1 = new KernelJAI(13, 13, _dmatrix);
        ParameterBlock pb1 = new ParameterBlock();
        pb1.addSource(_image);
        pb1.add(kernel1);
        _image = JAI.create("dilate", pb1);
        
        PlanarImage img = ie.getImage();
		KernelJAI kernel = new KernelJAI(13, 13, _ematrix);
		ParameterBlock pb = new ParameterBlock();
		pb.addSource(img);
		pb.add(kernel);
		_image = JAI.create("erode", pb);
		notifyListeners();

	}
}
